package com.yanftch.hdc_tools.insertcode.ui;

import com.yanftch.hdc_tools.insertcode.bean.CodeBean;

import javax.swing.*;

public class InsertCodeSettingsForm {
    private JComboBox comboBox;
    private JPanel insertRoot;
    private JTextField diyInputText;
    private JTextArea textArea;

    // 格式化输入的内容
    private JButton buttonFormat;
    private JScrollPane scrollPanel;

    public InsertCodeSettingsForm() {
        comboBox.setMaximumRowCount(15);//设置最大显示条目数量
        scrollPanel.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        textArea.setLineWrap(true);// 自动换行
        textArea.setWrapStyleWord(true);// 在单词边界换行

        buttonFormat.addActionListener(actionEvent -> format());

        comboBox.addActionListener(actionEvent -> {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    Object selectedItem = comboBox.getSelectedItem();
                    if (selectedItem instanceof CodeBean) {
                        CodeBean codeBean = (CodeBean) selectedItem;
                        textArea.setText(codeBean.getValue());
                    }
                }
            });
        });
    }

    private void format() {
        String text = textArea.getText();
        if (null == text || text.isEmpty()) {
            return;
        }
        // 按 "." 进行拆分
        String[] parts = text.split("\\.");

        // 拼接拆分后的字符串，每个部分换行
        StringBuilder newText = new StringBuilder();
        for (String part : parts) {
            if (newText.length() > 0) {
                newText.append(".");
            }
            newText.append(part);
            newText.append("\n");  // 每部分后面加上换行符
        }

        // 将新文本设置回 JTextArea
        textArea.setText(newText.toString());
    }

    public JPanel getMainPanel() {
        return this.insertRoot;
    }

    public JComboBox getComboBox() {
        return this.comboBox;
    }

    public JTextField getDiyName() {
        return this.diyInputText;
    }

    public JTextArea getDiyCodeContent() {
        return this.textArea;
    }
}
